<template>
  <el-date-picker
    v-model="currValue"
    type="daterange"
    style="width: 100%"
    :format="props.format"
    :value-format="props.valueFormat"
    range-separator="至"
    :start-placeholder="props.label + '开始日期'"
    :end-placeholder="props.label + '结束日期'"
    :clearable="props.clearable"
    @change="handleChange"
    @blur="handleBlur"
  />
</template>

<script setup>
import {ref, watch, onBeforeMount} from 'vue';

const emit = defineEmits(['update:modelValue', 'change', 'blur']);
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  format: {
    type: String,
    default: 'YYYY-MM-DD'
  },
  valueFormat: {
    type: String,
    default: 'YYYY-MM-DD'
  },
  clearable: {
    type: Boolean,
    default: true
  },
  label: {
    type: String,
    default: ''
  },
  showText: Boolean,
});

const currValue = ref([]);

const handleChange = ($event) => {
  updateValue(currValue.value);
  emit('change', $event);
};

const handleBlur = ($event) => {
  updateValue(currValue.value);
  emit('blur', $event);
};

const updateValue = (value) => {
  if (value && value.length > 0) {
    emit('update:modelValue', value.join(","));
  } else {
    emit('update:modelValue', '');
  }
};

const setCurrValue = (value) => {
  if (value && value.indexOf(",") > 0) {
    currValue.value = value.split(",");
  } else {
    currValue.value = [];
  }
};

watch(() => props.modelValue, (newVal) => {
  setCurrValue(newVal);
});

onBeforeMount(() => {
  setCurrValue(props.modelValue);
});
</script>

<style scoped>
</style>